// ==UserScript==
// @name					context-menu-dev
// @namespace               https://user-web.googlecode.com/
// @description				Add to context menu
// @include                 https://localhost:44300/TestLivexx.htm
// @version					2
// @grant					GM_openInTab
// ==/UserScript==

try {
    function initMenu(aEvent) {
        // aEvent.target is the element you right click on
        var node = aEvent.target;

        //if (node.localName == "img") {
        var item = document.querySelectorAll("#my-menu menuitem");
        body.setAttribute("contextmenu", "my-menu");

        for (var i = item.length - 1; i > -1; i--) {
            item[i].setAttribute("targetNode", node.tagName);
        }
        //}
        //else {
        //body.removeAttribute("contextmenu");
        ////item.removeAttribute("imageURL");
        //}
    }

    function searchImage(aEvent) {
        // Executed when user click on menuitem aEvent.target is the <menuitem> element
        log("menu a", aEvent.target.getAttribute("targetNode"));
    }

    function search_baidu(aEvent) {
        log("menu b", aEvent.target.getAttribute("targetNode"));
    }

    //if (!("contextMenu" in document.documentElement && "HTMLMenuItemElement" in window)) return;
    log("11");

    var body = document.body;
    body.addEventListener("contextmenu", initMenu, false);

    var menu = body.appendChild(document.createElement("menu"));
    menu.outerHTML = 
        '<menu id="my-menu" type="context">' +
        ' <menu label="sub">' +
		'  <menuitem id="SearchGoogle" label="Search this image"' +
		'   icon="">' +
		'  </menuitem>' +
		'  <menuitem id="SearchBaidu" label="Search this Baidu"></menuitem>' +
		' </menu>' +
		'</menu>';
    log("22");

    document.querySelector("#SearchGoogle").addEventListener("click", searchImage, false);
    document.querySelector("#SearchBaidu").addEventListener("click", search_baidu, false);
    log("33");
}
catch (ex) {
    if (ex.message.indexOf("accessing a cross-origin frame") > -1) {
        log("frame", ex.message);
    }
    else {
        log("error", ex.message);
    }
}

function log(text1, text2) {
    if (text2 != null) {
        if (text1.length < 20) {
            text1 = text1 + Array(21 - text1.length).join(" ");
        }

        if (text1.length > 20) {
            text1 = text1.substr(0, 20);
        }

        text1 = text1 + ": " + text2;
    }

    if (text1.length > 100) {
        text1 = text1.substr(0, 100) + "...";
    }

    console.log("[img-search] " + text1);
};
